# Copyright (c) 2012 Nathan Grubb
# Available under the new BSD license; see LICENSE.txt

"""plugin/logging.py: The logger for the bot; it functions simply as a plugin which 
   receives every type of IRC command and records it nicely.
"""

import datetime
import os

class Logging(object):
    """Messages are logged one-by-one and recorded into individual channel logs
       as well as being printed onto the console. 
    """

    commands = ("privmsg", "kick", "nick", "join", "part", "mode", "topic")
    name = "Logger"
    desc = "Internal plugin to log IRC events prettily."
    permissions = None
    type = "irc"

    def __init__(self, api, msg):
        self.api = api
        self.msg = msg

    def get_time(self):
        """Returns the current time in an appropriate format for logging [HH:MM]
        """
        
        time = datetime.datetime.time(datetime.datetime.now()).strftime("%I:%M %p")
        return "[%s] " % time

    def get_file(self, channel):
        """Returns the correct log to write to determined by channel and the
           current date. The current date is always written in the YYYY-MM-DD
           format.
        """
        
        d = datetime.date.today()
        date = d.strftime("%Y-%m-%d")
        filename = channel + "_" + date
        path = os.path.join(self.api.grubbot.grubbot_dir, "logs/", filename)
        return open(path, "a")

    def log(self, file, line):
        file.write(line+"\n")
        file.close()
        print line

    def flog(self, line, channel):
        """Formats the line to be logged by prefixing the time and channel, then logs."""

        line = self.get_time() + channel + " " + line
        file = self.get_file(channel)
        self.log(file, line)

    def command_privmsg(self):
        line = "<%s> %s" % (self.msg.nickname, self.msg.message)
        self.flog(line, self.msg.channel)

    def command_join(self):
        line = "%s has joined" self.msg.nickname
        self.flog(line, self.msg.channel)

    def command_topic(self):
        line = "%s has changed the topic to: %s" % (self.msg.nickname, self.msg.topic)
        self.flog(line, self.msg.channel)

    def command_part(self):
        line = "%s has left (%s)" % (self.msg.nickname, self.msg.reason)
        self.flog(line, self.msg.channel)

    def command_mode(self):
        line = "%s has set mode %s%s " % (self.msg.nickname, self.msg.mode_plusminus,
                                          self.msg.mode)

        if self.msg.nicknames:
            if len(self.msg.nicknames) > 1:
                firstset = self.msg.nicknames[:-1]
                lastone = self.msg.nicknames[-1]
                join = ", ".join(firstset)
                join += " and " + lastone
            else:
                join = self.msg.nicknames[0]

            line += "on users %s" % join
        else:
            line += "on channel %s" % self.msg.channel

        self.flog(line, self.msg.channel)

    def command_kick(self):
        line = "%s was kicked by %s (%s)" % (self.msg.kicked_nickname, 
                                             self.msg.nickname,
                                             self.msg.reason)
        self.flog(line, self.msg.channel)

    def command_quit(self):
        channels = self.api.get_channels(self.msg.nickname)
        
        for channel in channels:
            line = "%s has quit (%s)" % (self.msg.nickname, self.msg.reason)
            self.flog(line, channel)

    def command_nick(self):
        channels = self.api.get_channels(self.msg.new_nickname)

        for channel in channels:
            line = "%s has changed nick to %s" % (self.msg.nickname, 
                                                  self.msg.new_nickname)
            self.flog(line, channel)

plugin = Logging